<template>
    <div class="videoPlayer">
        <video ref="videoRef" class="video-js vjs-default-skin vjs-big-play-centered" controls>
            <source :src="path" />
        </video>
    </div>
</template>
<script setup>
import { nextTick, onBeforeUnmount, onMounted, ref, watch,defineExpose } from 'vue';
import videojs from 'video.js'
import 'video.js/dist/video-js.css'
import zh from "video.js/dist/lang/zh-CN.json"
const props = defineProps({
    path: {
        type: String,
        required: true,
        default: '',
    },
    autoplay: {
        type: Boolean,
        default: false,
    },
    poster:{
        type: String,
        default: '',
    },
    w: {
        type: Number,
        default: 1200,
    },
    h: {
        type: Number,
        default: 675,
    }
})
const videoRef = ref()
let player = null;
let videoPoster = "";
const emit = defineEmits(['ended','error','timeupdate','seeking','ready','loadedmetadata'])
const initPlayer = async () => {
    videojs.addLanguage('zh-CN',zh)
    await nextTick()
    const options = {
        width:props.w,
        height:props.h,
        poster:props.poster,
        autoplay: props.autoplay,
        playbackRates: [0.5, 1, 1.5, 2],
        language: 'zh-CN',
        preload: 'auto', // 预加载
        notSupportedMessage: 'Ajiang此视频暂无法播放，请稍后再试',
        controlBar: {
            children: [ //自定义controlBar内容显示顺序
                { name: 'playToggle' },
                { name: 'progressControl' },
                { name: 'remainingTimeDisplay', displayNegative:false }, //默认情况下，剩余时间显示为负时间。不显示负号 controlBar.remainingTimeDisplay.displayNegative 设置为 false。
                { name: 'playbackRateMenuButton', playbackRates: [0.5, 1, 1.5, 2] },
                { name: 'volumePanel',inline: false},
                { name: 'pictureInPictureToggle' },
                // {name: 'AutoPlayNext'},     //控制是否自动播放下一个
                { name: 'fullscreenToggle' }
            ],
        }
    };
    player = videojs(videoRef.value, options, () => {
        videojs.log('播放器已经准备好了!');
        if(props.poster){
            videoPoster = props.poster;
        }else{
            videoPoster = getPoster();
        }
        if (props.autoPlay && props.path) {
            player.play()
        }
        player.on('ready', () => {
            emit('ready')
            videojs.log('ready!');
        });
        player.on('ended', () => {
            emit('ended',parseInt(player.currentTime()))
            videojs.log('播放结束了!');
        });
        player.on('error', () => {
            emit('error')
            videojs.log('播放器解析出错!');
        })
        player.on('seeking', () => {
            emit('seeking')
            // videojs.log('每次当视频跳到一个新的时间都会触发!');
        })
        player.on('timeupdate', () => {
            emit('timeupdate',parseInt(player.currentTime()))
            // videojs.log('当当前的播放位置改变的时候触发!');
        })
        player.on('loadedmetadata', () => {
            emit('loadedmetadata')
        })
    });
}
const getPoster = ()=>{
    videoRef.value.currentTime = 1;
    // 创建canvas元素
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    // canvas画图
    canvas.width = props.w
    canvas.height = props.h
    ctx?.drawImage(videoRef.value, 0, 0, canvas.width, canvas.height)
    // 把canvas转成base64编码格式
    return canvas.toDataURL('image/png')
}
    //方法
    const operation = (param,info)=> {
        //console.log(param)
        if ("play" === param) {	//开始播放
            player.play();
        } else if ("stop" === param) {	//停止播放
            player.pause();
        } else if ("fastForward" === param) { //快进
            let whereYouAt = player.currentTime();
            player.currentTime(10 + whereYouAt);
        } else if ("reload" === param) {	//重新加载
            player.pause();
            player.load();
            player.play();
        } else if ("back" === param) {	//后退
            let whereYouAt = player.currentTime();
            player.currentTime(whereYouAt - 10);
        } else if ("fullScreen" === param) {	//全屏
            player.requestFullscreen();
        } else if ("exitFullScreen" === param) {	//退出全屏
            player.exitFullscreen();
        } else if ("volumeUp" === param) {	//音量加
            let howLoudIsIt = player.volume();
            player.volume(howLoudIsIt + 10);
        } else if ("volumeDown" === param) {	//音量减
            let howLoudIsIt = player.volume();
            console.log(howLoudIsIt)
            player.volume(howLoudIsIt - 10);
        } else if ("reset" === param) {	//重置，视频不会播放	
            player.reset();
        }else if ("setTime" === param) {	//设置播放进度
            player.play();
            player.currentTime(info);
        }
    }
onMounted(() => {
    initPlayer()
})
watch(() => props.path, () => {
    player.pause()
    player.src(props.path)
    player.load()
    if (props.path) {
        player.play()
    }
})
onBeforeUnmount(() => {
    player?.dispose()
})
defineExpose({
    operation
})
</script>
<style lang="scss">
.video-js .vjs-big-play-button {
  font-size: 2.5em !important;
  line-height: 2.3em !important;
  height: 2.5em !important;
  width: 2.5em !important;
  -webkit-border-radius: 2.5em !important;
  -moz-border-radius: 2.5em !important;
  border-radius: 2.5em !important;
  background-color: #73859f;
  background-color: rgba(115, 133, 159, 0.5) !important;
  border-width: 0.15em !important;
  margin-top: -1.25em !important;
  margin-left: -1.75em !important;
}
.vjs-big-play-button .vjs-icon-placeholder {
  font-size: 1.63em !important;
}
</style>
